package com.practice.designMode.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电视台，在这个demo中相当于一个事件总线
 */
public class TVStation {

    private List<User> users = new ArrayList<>();

    private Map<Class<? extends Event>,List<EventListener>> eventListeners = new HashMap<>();

    public void subsribe(EventListener listener,Class<? extends Event> eventClass){
        eventListeners.computeIfAbsent(eventClass,k -> new ArrayList<>()).add(listener);
    }

    public void publish(Event event){
        Class<? extends Event> eventClass = event.getClass();
        List<EventListener> eventListeners = this.eventListeners.get(eventClass);
        if(eventListeners != null){
            eventListeners.forEach(listener -> listener.onEvent(event));
        }
    }
}
